package com.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
 * 公平锁 实现 交替打印
 * @author yaojinshan
 * 2018-04-03 14:54 
 */
public class FairReentrantLockTest {
	public static void main(String[] args) {
		final Lock lock = new ReentrantLock(true); //参数 true 代表创建公平锁，不传参数则创建非公平锁
		FairLock fairLock = new FairLock(lock);
		new Thread(fairLock, "---").start();
		new Thread(fairLock, "--------").start();
	}
}
class FairLock implements Runnable{
	final Lock lock;
	
	static int currentNum = 0;
	public FairLock(Lock lock) {
		this.lock = lock;
	}

	static void increate(){
		currentNum++;
	}
	
	static int getCurrentNum(){
		return currentNum;
	}
	public void run() {
		while(getCurrentNum() < 100){
			lock.lock();
			try {
				System.out.println(Thread.currentThread().getName() + "输出：" +  getCurrentNum());
				increate();
			}finally{
				lock.unlock();
			}
		}
	}
}
